package com.hitqz.robot.biz.aop;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.Cache;
import com.hitqz.robot.api.business.dto.RemoteControlAuthDto;
import com.hitqz.robot.api.business.dto.RobotControlButtonDto;
import com.hitqz.robot.api.common.entity.Robot;
import com.hitqz.robot.biz.config.GuavaCacheConfig;
import com.hitqz.robot.biz.service.RobotService;
import com.hitqz.robot.common.core.util.R;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;
import java.util.Objects;

import static com.hitqz.robot.biz.config.GuavaCacheConfig.CACHE_CONST;
import static com.hitqz.robot.biz.config.GuavaCacheConfig.REMOTE_CONTROL_AUTH;

@Aspect
@Component
@Slf4j
@AllArgsConstructor
public class ClientIdAspect {


    private final Cache<String, Boolean> remoteControlAuthCache;

    @Around("@annotation(RemoteControlAuthTag)") // 拦截所有带@ClientIdRequired注解的方法
    public Object validateClientId(ProceedingJoinPoint joinPoint) throws Throwable {

// 1. 获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        // 2. 获取方法对象
        Method method = signature.getMethod();

        // 3. 获取参数名发现器
        ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
        String[] parameterNames = parameterNameDiscoverer.getParameterNames(method);
        // 检查clientId参数是否存在
        // 4. 获取参数值
        RobotControlButtonDto dto = (RobotControlButtonDto) joinPoint.getArgs()[0];
        String source = (String) joinPoint.getArgs()[1];

        if (!Objects.isNull(dto) && !Objects.equals(dto.getAction(), "releaseRemoteControlAuth")
                && "android".equals(source) && Boolean.TRUE.equals(remoteControlAuthCache.getIfPresent(REMOTE_CONTROL_AUTH))) {
            remoteControlAuthCache.put(REMOTE_CONTROL_AUTH, Boolean.TRUE);

        }
        if( "android".equals(source)&& !Boolean.TRUE.equals(remoteControlAuthCache.getIfPresent(REMOTE_CONTROL_AUTH))&&
                !Objects.isNull(dto) && !Objects.equals(dto.getAction(), "remoteControlAuth")
        ){
            return R.failed("请先取得控制权");
        }
        return joinPoint.proceed();


    }
}